<template>
  <div class="topbar">
    <span class="title">{{ appTitle }}</span>
    <div class="right-section">
      <span class="mqtt-status" :class="{ connected: isAvailable }">
        {{ statusText }}
      </span>
      <span class="datetime">{{ formattedTime }}</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useMQTT } from '../composables/useMQTT'
import { APP_CONFIG, MQTT_CONFIG } from '../config/mqtt'

const formattedTime = ref('')
const appTitle = ref(APP_CONFIG.DEFAULT_TITLE)

const updateTime = (): void => {
  const now = new Date()
  formattedTime.value = `${now.getFullYear()}/${String(now.getMonth() + 1).padStart(2, '0')}/${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`
}

// 使用MQTT组合式函数
const{
  isAvailable,
  statusText,
  appInfo,
  connect,
  requestAppInfo
} = useMQTT()

// 监听应用信息更新，动态更新标题
watch(appInfo, (newAppInfo) => {
  if (newAppInfo && newAppInfo.appName && newAppInfo.appVersion) {
    appTitle.value = APP_CONFIG.TITLE_FORMAT
      .replace('{appName}', newAppInfo.appName)
      .replace('{appVersion}', newAppInfo.appVersion)
    console.log('应用标题已更新:', appTitle.value)
  }
})

onMounted(async () => {
  updateTime()
  const timer = setInterval(updateTime, 1000)
  
  // 连接MQTT
  const connected = await connect({
    brokerUrl: MQTT_CONFIG.BROKER_URL,
    username: MQTT_CONFIG.USERNAME,
    password: MQTT_CONFIG.PASSWORD,
    clientId: `${MQTT_CONFIG.CLIENT_ID_PREFIX}-${Date.now()}`
  })
  
  if (connected) {
    // 请求应用信息
    await requestAppInfo()
  }
  
  onUnmounted(() => {
    clearInterval(timer)
  })
})
</script>

<style scoped>
.topbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background: #f5f5f5;
  border-bottom: 1px solid #ddd;
}
.title {
  color: #00050b;
  font-weight: normal;
  font-size: 16px;
}
.datetime {
  color: #888;
  font-size: 14px;
}
.mqtt-status {
  color: #ff4d4f;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
  background: rgba(255, 77, 79, 0.1);
  border: 1px solid rgba(255, 77, 79, 0.3);
}
.mqtt-status.connected {
  color: #52c41a;
  background: rgba(82, 196, 26, 0.1);
  border: 1px solid rgba(82, 196, 26, 0.3);
}
.right-section {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>
